import axios from 'axios';
import qs from 'qs';
let config = process.env;
let base = config.NODE_ENV === 'development' ? 'http://localhost:12345' : 'http://passport.bilibili.com';

const API_BASE_URL = base, //'http://slp1.slzrsz.com:8888/api', // 域名
  SETDATA = false, //启动自动设置
  ISWEXIN = false, //是否小程序api
  INTERVAL = 3, //api频率间隔（秒），为0则不控频率
  //res.code非零提示
  showMsg = function (msg = '') {
    /*     wx.showToast({
          title: msg,
          icon: "none",
          duration: 4000
        }); */
  },
  NotShowMsg = ["/finish_tack"];

let service = null;
if (!ISWEXIN) {
  // axios = (await import("axios")).default;
  service = axios.create({
    // baseURL: BASE_URL,
    // timeout: 5000 // 请求超时时间
  });

  /**
   * 只有vue才有拦截api
   */
  service.interceptors.request.use(
    req => {
      // req.headers["X-Token"] = xxx
      // req.headers[ 'Content-Type'] = 'application/x-www-form-urlencoded';
      return req;
    },
    error => {
      // Do something with request error
      Promise.reject(error);
    }
  );
  service.interceptors.response.use(
    res => {
      var code = res.data.code
      if (code) {
        if (code === 2) {} else if (code == 3) {

        } else if (code == 4) {

        } else if (code == 5) {

        }
      }
      return res.data;
    },
    error => {
      console.log(error.message, "axios.js");

      return Promise.reject(error);
    }
  );
}

function isFrequent(url) {

  let timeStamp = String(+new Date()).slice(0, 10);
  let apiCalls = ISWEXIN ? wx.getStorageSync("API_FRE") || {} : JSON.parse(localStorage.getItem("API_FRE")) || {};
  let lastTimeStamp = apiCalls[url] || 0;
  if (lastTimeStamp) {
    if (timeStamp - lastTimeStamp < INTERVAL) {
      console.warn('调用接口[' + url + ']频率过快，至少间隔' + INTERVAL + '秒');
      return true;
    }
  }
  apiCalls[url] = timeStamp;
  ISWEXIN ? wx.setStorageSync("API_FRE", apiCalls) : localStorage.setItem("API_FRE", JSON.stringify(apiCalls));
  return false;
}
/**
 * set  不传或true时,page.data中生成url请求名的变量存数据;为字符串时,page.data中生成该字符串为名的变量存数据
 */
const api = (method = "get", url = "/", data = {}, set) => {
  let _url = /http/.test(url) ? url : API_BASE_URL + url;
  var promise = new Promise((resolve, reject) => {
    if (isFrequent(url) && INTERVAL) reject();
    const opt = {
      url: _url,
      method,
      data,
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
    }
    if (ISWEXIN) {
      //小程序api
      wx.request({
        ...opt,
        success(res) {
          _then(res.data);
          resolve(res.data); //去掉http头部
        },
        fail(err) {
          _catch(err)
          reject(err)
        },
        complete() {}
      })
    } else {
      //vue api
      if (method === 'get') {
        opt.params = opt.data;
        delete opt.data;
      }
      if(opt.header){
        opt.headers=opt.header;
        delete opt.header;
        if(opt.headers['Content-Type']=='application/x-www-form-urlencoded'){
          opt.data=qs.stringify(opt.data);
        }
      }
      service(opt)
        .then(res => {
          _then(res);
          resolve(res)
        })
        .catch(err => {
          _catch(err)
          reject(err)
        })
    }
  })

  function _then(res) {
    /*     console.log("调用接口：url:  " + url + "     success")
        console.log("         data:", data);
        console.log("         res:", res); */
    console.log('调用接口',{
      url: `${url}`,
      data: data,
      res: res
    })
    if (res.Code == 0) {
      let page = getCurrentPages()
      if (typeof set === 'undefined' && SETDATA || set === true) {
        let index = url.lastIndexOf("/")
        let urltemp = index > -1 ? url.substring(index + 1) : url;
        page[page.length - 1].setData({
          [urltemp]: res.data
        })
      } else if (set) {
        page[page.length - 1].setData({
          [set]: res.data
        })
      }
    }
    for (let i = 0; i < NotShowMsg.length; i++) {
      if (url === NotShowMsg[i]) return;
    }
    if (res.Code != 0) {
      showMsg(res.msg ? res.msg : 'res.code不为0');
    }
  };

  function _catch(err) {
    console.log(err, url + "     catcherror");
    let msg = 1;
    if (err && err.errMsg && err.errMsg.match('timeout')) {
      msg = "后台请求数据超时"
    } else {
      msg = err
    }
    showMsg(msg);
  };
  /* promise.then(res => {
        // console.log("调用接口：url:  " + url + "     success")
        // console.log("         data:", data);
        // console.log("         res:", res);
    console.log({
      url: `${url}     调用接口`,
      data: data,
      res: res
    })
    if (res.Code == 0) {
      let page = getCurrentPages()
      if (typeof set === 'undefined' && SETDATA || set === true) {
        let index = url.lastIndexOf("/")
        let urltemp = index > -1 ? url.substring(index + 1) : url;
        page[page.length - 1].setData({
          [urltemp]: res.data
        })
      } else if (set) {
        page[page.length - 1].setData({
          [set]: res.data
        })
      }
    }
    for (let i = 0; i < NotShowMsg.length; i++) {
      if (url === NotShowMsg[i]) return;
    }
    if (res.Code != 0) {
      showMsg(res.msg ? res.msg : 'res.code不为0');
    }
  }).catch(err => {
    console.log(err, url + "     catcherror");
    let msg = 1;
    if (err && err.errMsg && err.errMsg.match('timeout')) {
      msg = "后台请求数据超时"
    } else {
      msg = err
    }
    showMsg(msg);
  }) */
  return promise;
}

/**
 * 小程序的promise没有finally方法，自己扩展下
 */
Promise.prototype.finally = function (callback) {
  var Promise = this.constructor;
  return this.then(
    function (value) {
      Promise.resolve(callback()).then(
        function () {
          return value;
        }
      );
    },
    function (reason) {
      Promise.resolve(callback()).then(
        function () {
          throw reason;
        }
      );
    }
  );
}





//CommonJS
/* module.exports = {
  api,
  get: (url, data, set) => api('get', url, data, set),
  post: (url, data, set) => api('post', url, data, set)
} */
//ES6
export  {
  api
}
export function get(url, data, set){return api('get', url, data, set);} 
export function post(url, data, set){return api('post', url, data, set);} 


//重写element的Messeage弹窗
/* let messageInstance = null;
const resetMessage = (options) => {
    if (messageInstance) {
        messageInstance.close()
    }
    messageInstance = Message(options)
};
['error', 'success', 'info', 'warning'].forEach(type => {
    resetMessage[type] = options => {
        if (typeof options === 'string') {
            options = {
                message: options
            }
        }
        options.type = type
        return resetMessage(options)
    }
})
var message = resetMessage; */